require 'active_support'
require 'active_record'

module ActiveRecord
	module Acts #:nodoc:
		module Guided #:nodoc:
			GUID_LENGTH = 10


			def self.append_features(base)
				super
				base.extend(ClassMethods)
			end



			module ClassMethods
				def acts_as_guid(options = {})

					# now, finally add the proper relationships
					class_eval do
						include ActiveRecord::Acts::Guided::InstanceMethods
						extend ActiveRecord::Acts::Guided::SingletonMethods
						before_create :generate_guid
					end
				end
			end

			module SingletonMethods
				def create_guid_string
					chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
					result = ''
					1.upto(GUID_LENGTH) do |i|
						result << chars[rand(chars.size-1)]
					end
					return result

				end

				def generate_uniq_guid
					begin
						guid = create_guid_string
						g_rec = Guid.new(:guid => guid)
						g_rec.save!
						return guid
					rescue ActiveRecord::StatementInvalid => e
						retry
					end
				end
			end

			module InstanceMethods
				def generate_guid
					self.guid = self.class.generate_uniq_guid
				end
			end
		end
	end
end

ActiveRecord::Base.class_eval do
	include ActiveRecord::Acts::Guided
end
